package com.canlihao.ui.view.fragment;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.RemoteViews;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.core.content.FileProvider;


import com.canlihao.ui.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class UpdateService extends Service {

	//private String apkurl = "http://adm.jialesys.com/";
	private String apkPath;
	private String apkName;
	private boolean canceled = false;
	private NotificationManager manager;
	private Notification notification;
	String stringVal = "";
	String banbenName = "";
	CanceledReceiver cand;
	MyHandler myHandler;
	private static final int YOUR_NOTIFICATION_ID = 0x002;
	private static final String YOUR_CHANNEL_ID = "YOUR_NOTIFY_ID";
	private static final String YOUR_CHANNEL_NAME = "YOUR_NOTIFY_NAME";
	@Override
	public IBinder onBind(Intent intent) {
		//stringVal = intent.getStringExtra("url");
		//Log.i("lw","stringVal="+stringVal);
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Bundle bb = intent.getExtras();
		stringVal = bb.getString("url");
		banbenName = bb.getString("banbenName");
		new Thread(new DownApkRunnable()).start();
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public void onCreate() {
		super.onCreate();
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			apkPath = String.valueOf(getFilesDir());
			apkName = "doctor_lastest.apk";
			//registerBroader();
			myHandler = new MyHandler(this);
			setUpNotifiction();
			//new Thread(new DownApkRunnable()).start();
		} else {
			Toast.makeText(UpdateService.this, "SD卡不存在", Toast.LENGTH_SHORT)
					.show();
		}
	}
	@RequiresApi(api = Build.VERSION_CODES.O)
	public void CreateNotificationChannel(NotificationManager notificationManager) {
		NotificationChannel channel = new NotificationChannel(YOUR_CHANNEL_ID,YOUR_CHANNEL_NAME, notificationManager.IMPORTANCE_HIGH);
		notificationManager.createNotificationChannel(channel);
	}
	/**
	 * 创建通知
	 */
	private void setUpNotifiction() {
		manager = (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
		if (Build.VERSION.SDK_INT >= 26) {
			CreateNotificationChannel(manager);
			notification = new Notification.Builder(getApplicationContext(), YOUR_CHANNEL_ID).build();

		} else {
			notification = new Notification();
		}

		notification.icon = R.mipmap.launch_logo;
		notification.when = System.currentTimeMillis();
		notification.tickerText = "开始下载";

//		int icon = R.mipmap.small_logo_1;
//		CharSequence tickerText = "开始下载";
//		long when = System.currentTimeMillis();
//		notification = new Notification(icon, tickerText, when);
		RemoteViews contentView = new RemoteViews(getPackageName(),
				R.layout.notify_update_layout);
		contentView.setTextViewText(R.id.name, "\"小松云医\""+banbenName+"正在下载中...");
		notification.contentView = contentView;
//		Intent intent = new Intent(UpdateService.this, LoginActivity.class);
//		PendingIntent contentIntent = PendingIntent.getActivity(
//				UpdateService.this, 0, intent,
//				PendingIntent.FLAG_UPDATE_CURRENT);
//		notification.contentIntent = contentIntent;

		manager.notify(0, notification);// 发送通知
	}

	/**
	 * 取消接收者
	 * 
	 * @author renzhiwen 创建时间 2014-8-16 下午4:05:24
	 */
	class CanceledReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			if ("canceled".equals(intent.getStringExtra("canceled"))) {
				canceled = true;
				manager.cancel(0);
				stopSelf();
			}

		}

	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	/**
	 * 注册广播
	 */
	public void registerBroader() {
		IntentFilter filter = new IntentFilter();
		filter.addAction("canceled");
		cand = new CanceledReceiver();
		registerReceiver(cand, filter);
	}

	/**
	 * 下载apk
	 * 
	 * @author renzhiwen 创建时间 2014-8-16 下午3:32:34
	 */
	class DownApkRunnable implements Runnable {

		@Override
		public void run() {
			downloadApk();
		}

	}

	private int laterate = 0;

	private void downloadApk() {
		try {
			URL url = new URL(stringVal);

			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			int length = conn.getContentLength();
			int count = 0;
			File apkPathFile = new File(apkPath);
			if (!apkPathFile.exists()) {
				apkPathFile.mkdir();
			}
			File apkFile = new File(apkPath, apkName);
			InputStream in = conn.getInputStream();
			FileOutputStream os = new FileOutputStream(apkFile);
			byte[] buffer = new byte[1024];
			do {
				int numread = in.read(buffer);
				count += numread;
				int progress = (int) (((float) count / length) * 100);// 得到当前进度
				if (progress >= laterate + 1) {// 只有当前进度比上一次进度大于等于1，才可以更新进度
					laterate = progress;
					Message msg = new Message();
					msg.what = 1;
					msg.arg1 = progress;
					//handler.sendMessage(msg);
					myHandler.sendMessage(msg);
				}
				if (numread <= 0) {// 下载完毕
					//handler.sendEmptyMessage(2);
					myHandler.sendEmptyMessage(2);
					canceled = true;
					break;
				}
				os.write(buffer, 0, numread);
			} while (!canceled);// 如果没有被取消
			in.close();
			os.close();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.toString();
			e.printStackTrace();
		}

	}
  /* 创建静态内部类
  */
	private class MyHandler extends Handler {
		//持有弱引用HandlerActivity,GC回收时会被回收掉.
		private final WeakReference<UpdateService> mActivty;
		public MyHandler(UpdateService activity){
			mActivty =new WeakReference<UpdateService>(activity);
		}
		@Override
		public void handleMessage(Message msg) {
			UpdateService activity=mActivty.get();
			super.handleMessage(msg);
			if(activity!=null){
				//执行业务逻辑
				switch (msg.what) {
					case 1:// 更新进度
						int progress = msg.arg1;
						if (progress < 100) {
							RemoteViews contentView = notification.contentView;
							contentView.setTextViewText(R.id.tv_progress, progress
									+ "%");
							contentView.setProgressBar(R.id.progressbar, 100, progress,
									false);
						} else {// 下载完成，停止服务
							stopSelf();
						}
						manager.notify(0, notification);
						break;
					case 2:// 安装apk
						manager.cancel(0);
						installApk();
						break;

					default:
						break;
				}
			}
		}
	}

//	Handler handler = new Handler() {
//		public void handleMessage(Message msg) {
//			switch (msg.what) {
//			case 1:// 更新进度
//				int progress = msg.arg1;
//				if (progress < 100) {
//					RemoteViews contentView = notification.contentView;
//					contentView.setTextViewText(R.id.tv_progress, progress
//							+ "%");
//					contentView.setProgressBar(R.id.progressbar, 100, progress,
//							false);
//				} else {// 下载完成，停止服务
//					stopSelf();
//				}
//				manager.notify(0, notification);
//				break;
//			case 2:// 安装apk
//				manager.cancel(0);
//				installApk();
//				break;
//
//			default:
//				break;
//			}
//		}
//	};

	/**
	 * 安装apk
	 */
	private void installApk() {
		/*File apkFile = new File(apkPath, apkName);
		if (!apkFile.exists()) {
			return;
		}

		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(Intent.ACTION_VIEW);
		if (android.os.Build.VERSION.SDK_INT >= 24) {
			Log.i("lw","apkFile.toString()="+apkFile.toString());
			intent.setDataAndType(Uri.parse("content://" + apkFile.toString()),
					"application/vnd.android.package-archive");
		}else{
			intent.setDataAndType(Uri.parse("file://" + apkFile.toString()),
					"application/vnd.android.package-archive");
		}

		startActivity(intent);*/

		File file = new File(apkPath,apkName);

        Intent intent = new Intent();

		intent.setAction(Intent.ACTION_VIEW);

		if (Build.VERSION.SDK_INT >= 24)

		{ // Android7.0及以上版本 Log.d("-->最新apk下载完毕","Android N及以上版本");

			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

			intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

			Uri contentUri = FileProvider.getUriForFile(this, "com.canlihao.ui.FileProvider", file);

//参数二:应用包名+".fileProvider"(和步骤二中的Manifest文件中的provider节点下的authorities对应)

			intent.setDataAndType(contentUri, "application/vnd.android.package-archive");

		} else {

// Android7.0以下版本 Log.d("-->最新apk下载完毕","Android N以下版本");

			intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");

			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);}

		this.startActivity(intent);

	}
}
